from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from . import models, database
from pydantic import BaseModel
from datetime import datetime

router = APIRouter()


class ReviewBase(BaseModel):
    rating: int
    comment: str


class ReviewCreate(ReviewBase):
    user_id: int
    product_id: int


class Review(ReviewBase):
    id: int
    user_id: int
    product_id: int
    created_at: datetime

    class Config:
        orm_mode = True


@router.post("/reviews/", response_model=Review)
def create_review(review: ReviewCreate, db: Session = Depends(database.get_db)):
    # 检查用户是否存在
    user = db.query(models.User).filter(
        models.User.id == review.user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    # 检查商品是否存在
    product = db.query(models.Product).filter(
        models.Product.id == review.product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="Product not found")

    # 检查评分是否有效
    if not 1 <= review.rating <= 5:
        raise HTTPException(
            status_code=400, detail="Rating must be between 1 and 5")

    # 检查用户是否已经评价过该商品
    existing_review = db.query(models.Review).filter(
        models.Review.user_id == review.user_id,
        models.Review.product_id == review.product_id
    ).first()

    if existing_review:
        raise HTTPException(
            status_code=400, detail="User has already reviewed this product")

    # 创建评价
    db_review = models.Review(**review.dict())
    db.add(db_review)
    db.commit()
    db.refresh(db_review)
    return db_review


@router.get("/products/{product_id}/reviews/", response_model=List[Review])
def get_product_reviews(product_id: int, db: Session = Depends(database.get_db)):
    reviews = db.query(models.Review).filter(
        models.Review.product_id == product_id).all()
    return reviews


@router.get("/users/{user_id}/reviews/", response_model=List[Review])
def get_user_reviews(user_id: int, db: Session = Depends(database.get_db)):
    reviews = db.query(models.Review).filter(
        models.Review.user_id == user_id).all()
    return reviews


@router.put("/reviews/{review_id}", response_model=Review)
def update_review(review_id: int, review: ReviewBase, db: Session = Depends(database.get_db)):
    db_review = db.query(models.Review).filter(
        models.Review.id == review_id).first()
    if not db_review:
        raise HTTPException(status_code=404, detail="Review not found")

    if not 1 <= review.rating <= 5:
        raise HTTPException(
            status_code=400, detail="Rating must be between 1 and 5")

    for key, value in review.dict().items():
        setattr(db_review, key, value)

    db.commit()
    db.refresh(db_review)
    return db_review


@router.delete("/reviews/{review_id}")
def delete_review(review_id: int, db: Session = Depends(database.get_db)):
    db_review = db.query(models.Review).filter(
        models.Review.id == review_id).first()
    if not db_review:
        raise HTTPException(status_code=404, detail="Review not found")

    db.delete(db_review)
    db.commit()
    return {"message": "Review deleted successfully"}
